package com.example.mytips.findWidget;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBScrollPane;
import org.apache.http.util.TextUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.*;
import java.util.List;

public class FlutterWidgetDialog extends DialogWrapper {

    private int groupWidth = 200;

    private int width = 850;
    private int height = 2024;

    private int methodNameWidth = 220;

    private JBScrollPane leftPanel;

    private JBScrollPane rightPanel;

    private JBList<FindWidgetEntity> rightList;


    public FlutterWidgetDialog(AnActionEvent e, List<FindWidgetEntity> list) {
        super(true);

        ///上下文
        DataContext context = e.getDataContext();

        ///当前文件
        PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(context);

        //编辑器
        Editor editor = CommonDataKeys.EDITOR.getData(context);

        Map<String, List<FindWidgetEntity>> groupMap = new HashMap<>();
        // 组建数据
        for (FindWidgetEntity entity : list) {
            String groupName = entity.groupName;
            if (groupMap.containsKey(groupName)) {
                List<FindWidgetEntity> groupChildList = groupMap.get(groupName);
                groupChildList.add(entity);
            } else {
                List<FindWidgetEntity> groupChildList = new ArrayList<>();
                groupChildList.add(entity);
                groupMap.put(groupName,groupChildList);
            }
        }

        String[] groupList = groupMap.keySet().toArray(String[]::new);

        JBList<String> subDirList = new JBList<>(groupList);
        subDirList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        subDirList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    String key = subDirList.getSelectedValue();

                    List<FindWidgetEntity> findWidgetEntities = groupMap.get(key);
                    rightList.setListData(findWidgetEntities.toArray(FindWidgetEntity[]::new));
                }
            }
        });

        ///布局
        rightList = new JBList<>();
        rightList.setCellRenderer(new ListCellRenderer<FindWidgetEntity>() {
            @Override
            public Component getListCellRendererComponent(JList<? extends FindWidgetEntity> list, FindWidgetEntity value, int index,
                                                          boolean isSelected, boolean cellHasFocus) {
                // 创建水平布局的面板
                JPanel panel = new JPanel();
                panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));


                ///这是方法名
                JLabel name = new JLabel(value.className);

                ///设置最大宽高
                name.setMaximumSize(new Dimension(methodNameWidth, 30));
                name.setMinimumSize(new Dimension(methodNameWidth, 30));

                ///设置宽高
                Dimension preferredSize = new Dimension(methodNameWidth, 30);
                name.setPreferredSize(preferredSize);

                ///文本颜色
                //name.setForeground(Color.WHITE);
                ///字体
                name.setFont(new Font("Arial",Font.PLAIN,14));

                ///背景颜色
                if (index % 2 == 0) {
                    panel.setBackground(new Color(54,54,54));
                } else {
                    panel.setBackground(new Color(28,28,28));
                }

                panel.add(name);

                ///注释
                if (!TextUtils.isEmpty(value.note)) {
                    String noteStr = value.note;
                    //noteStr = "在上述代码中，我们创建了一个JFrame和一个JPanel。在JPanel中，我们使用FlowLayout布局管理器，它会根据组件的大小和位置自动布局。然后，我们创建一个JLabel，并使用setFont()方法设置其字体，通过调整字体的大小和样式来间接控制行高。接下来，我们使用setBorder()方法设置一个具有10像素上下内边距的边框，以增加行高。最后，我们将JLabel添加到JPanel中，并将JPanel添加到JFrame中。调用pack()方法可以根据组件的大小自动调整JFrame的大小";
                    JLabel note = new JLabel(noteStr);
                    note.setForeground(new Color(0,255,0,150));
                    panel.add(note);

                }

                return panel;
            }
        });

        ///点击事件
        rightList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                if (mouseEvent.getClickCount() == 1) {
                    // 获取子目录名称
                    FindWidgetEntity entity = rightList.getSelectedValue();
                    System.out.println("文件：" + entity.path + " , 类名:" + entity.className + " ,行数：" + entity.line);


                    ///打开文件
                    // 获取文件对象
                    File file = new File(entity.path);
                    // 获取文件的VirtualFile对象
                    VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file);
                    if (virtualFile != null) {
                        // 打开文件
                        FileEditorManager.getInstance(e.getProject()).openFile(virtualFile, true);

                        ///将光标定位到指定行
                        editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(entity.line, 0));
                        editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
                        doOKAction();
                    }
                }
            }
        });

        // 创建左侧面板
        leftPanel = new JBScrollPane(subDirList);
        leftPanel.setPreferredSize(new Dimension(groupWidth, height));

        // 创建右侧面板
        rightPanel = new JBScrollPane(rightList);
        rightPanel.setPreferredSize(new Dimension(width - groupWidth, height));

        // 设置对话框界面布局
        setTitle("查询组件");
        // 固定窗口大小
        setResizable(false);
        // 窗口大小
        setSize(width, height);
        pack();
        // 初始化对话框内容
        init();

    }

    @Override
    protected @NonNls @org.jetbrains.annotations.Nullable String getDimensionServiceKey() {
        return "FlutterWidgetDialog";
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        // 创建中心面板
        JBPanel centerPanel = new JBPanel(new BorderLayout());

        // 添加左侧面板和右侧面板到中心面板
        centerPanel.add(leftPanel, BorderLayout.WEST);
        centerPanel.add(rightPanel, BorderLayout.CENTER);

        return centerPanel;
    }
}
